package com.wayne.oauth2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wayne.oauth2.entity.UserAuth;
import com.wayne.oauth2.mapper.UserAuthMapper;
import com.wayne.oauth2.service.UserAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserAuthServiceImpl implements UserAuthService {
    @Autowired
    private UserAuthMapper userAuthMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<UserAuth> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserAuth::getIdentifier, username);
        UserAuth userAuth = userAuthMapper.selectOne(queryWrapper);
        if (userAuth == null) {
            throw new UsernameNotFoundException("账号不存在");
        }
        //权限不能为空
        List<GrantedAuthority> list = AuthorityUtils.commaSeparatedStringToAuthorityList("ROOT_USER");
        User user = new User(userAuth.getIdentifier(), userAuth.getCredential(), list);
        return user;
    }
}